from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from selenium.webdriver.chrome.service import Service 
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.common.keys import Keys
from selenium.webdriver.common.by import By
from selenium.webdriver.support import expected_conditions as EC
import json

from ApiBase import apiBase
quest= apiBase.argv_json(1,"python")
web= apiBase.argv_json(2,{"url":"https://www.baidu.com/","input":"kw","btn":"su"})

# 初始化无界面浏览器选项
options = Options()
# 启用无头模式
options.add_argument('--headless')
options.add_argument('--no-sandbox')
# options.add_argument('--disable-gpu')
# options.add_argument('--disable-dev-shm-usage')
options.add_argument('--remote-debugging-port=9222')
# 创建 WebDriver 对象
service = Service(executable_path='/home/softrobot/llm/qwne05/chromedriver-linux64/chromedriver')
driver = webdriver.Chrome(service=service,options=options)
ret=[]
try:
    # 打开百度首页
    driver.get('https://www.baidu.com/')
    # 找到搜索输入框，输入"python"
    driver.find_element(By.ID, 'kw').send_keys('python')
    # 找到"百度一下"按钮，并点击
    driver.find_element(By.ID, 'su').click()
    # 等待搜索结果加载完成
    driver.implicitly_wait(10)
    # 获取搜索结果列表
    # results = driver.find_elements(By.CSS_SELECTOR, '.result a')
    # for i in range(5):
    #     result_url = results[i].get_attribute('href')
    #     print(result_url)
    #     text = results[i].get_attribute('h3')
    #     print(text)
    # 限制获取前 10 条结果
    results = driver.find_elements(By.CSS_SELECTOR, '.result')
    top_results = results[:6]
    
    # 遍历前 10 条结果，提取标题和摘要信息
    for idx, result in enumerate(top_results, start=1):
        try:
            # 获取标题
            #title = result.find_element(By.CSS_SELECTOR, "h3").text
            # 获取摘要
            data={}
            data["id"] = idx
            data["content"] = result.text
            ret.append(data)
            #print("-" * 50)
        except Exception as e:
            print(f"Error processing result {idx}: {e}")
finally:
    # 关闭浏览器
    driver.quit()
print(json.dumps(ret, ensure_ascii=False)